import { API_CONFIG } from '@/config'
import type { 
  ApiResponse, 
  PlaybackQueryParams, 
  PlaybackQueryResponse, 
  PlaybackRecord,
  StreamServer,
  PlaybackStreamIdResponse,
  PlaybackTokenParams
} from '@/types'

/**
 * 录像查询API服务类
 * 支持动态获取IP和端口进行录像查询
 */
export class PlaybackApiService {
  private streamServers: StreamServer[] = []
  private recordStreamPort: string = ''

  constructor() {
    // 初始化时使用默认配置
  }

  /**
   * 设置流媒体服务器信息
   * @param servers 流媒体服务器列表
   * @param port 录像流端口
   */
  setStreamServers(servers: StreamServer[], port: string) {
    this.streamServers = servers
    this.recordStreamPort = port
    
    console.log('录像查询服务器信息已设置:', {
      serversCount: servers.length,
      servers: servers.map(s => ({ id: s.id, ip: s.ip, name: s.name })),
      recordStreamPort: port
    })
  }

  /**
   * 根据nvrId获取对应的流媒体服务器
   * @param nvrId NVR ID
   * @returns 流媒体服务器信息
   */
  private getStreamServerByNvrId(nvrId: number): StreamServer | null {
    console.log('查找流媒体服务器:', {
      nvrId,
      availableServers: this.streamServers.map(s => ({ id: s.id, ip: s.ip, name: s.name }))
    })
    
    const server = this.streamServers.find(server => server.id === nvrId) || null
    
    if (server) {
      console.log('找到匹配的流媒体服务器:', server)
    } else {
      console.warn('未找到匹配的流媒体服务器，nvrId:', nvrId)
    }
    
    return server
  }

  /**
   * 构建录像查询URL
   * @param nvrId NVR ID
   * @returns 完整的录像查询URL
   */
  private buildPlaybackUrl(nvrId: number): string {
    const server = this.getStreamServerByNvrId(nvrId)
    if (!server) {
      throw new Error(`未找到NVR ID ${nvrId} 对应的流媒体服务器`)
    }

    // 在开发环境使用代理，生产环境直接访问
    if (import.meta.env.DEV) {
      // 使用Vite代理，通过 /playback 路径访问
      return `/playback${API_CONFIG.ENDPOINTS.PLAYBACK.QUERY_VOD}`
    } else {
      // 生产环境直接访问录像服务器
      const protocol = API_CONFIG.PLAYBACK_SERVER.PROTOCOL
      const host = server.ip
      const port = this.recordStreamPort || API_CONFIG.PLAYBACK_SERVER.PORT
      
      return `${protocol}://${host}:${port}${API_CONFIG.ENDPOINTS.PLAYBACK.QUERY_VOD}`
    }
  }

  /**
   * 查询录像记录
   * @param params 查询参数
   * @returns 录像记录列表
   */
  async queryVodRecords(params: PlaybackQueryParams): Promise<ApiResponse<PlaybackQueryResponse>> {
    try {
      console.log('开始录像查询:', {
        EquId: params.EquId,
        nvrId: params.nvrId,
        ChannelId: params.ChannelId,
        StartTime: params.StartTime,
        EndTime: params.EndTime
      })
      
      // 构建查询参数（不使用URLSearchParams避免编码）
      const queryParams = [
        `EquId=0`,
        `ChannelId=${params.ChannelId}`,
        `StartTime=${params.StartTime}`,
        `EndTime=${params.EndTime}`
      ].join('&')

      // 使用动态构建的URL（使用nvrId匹配服务器）
      const baseUrl = this.buildPlaybackUrl(params.nvrId)
      const url = `${baseUrl}?${queryParams}`
      
      console.log('录像查询URL:', url)
      console.log('环境模式:', import.meta.env.DEV ? '开发环境(使用代理)' : '生产环境(直接访问)')
      
      // 使用fetch直接请求录像服务器，因为这是特定的IP和端口
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        // 设置超时
        signal: AbortSignal.timeout(API_CONFIG.REQUEST_CONFIG.TIMEOUT)
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      
      // 将服务器响应转换为标准格式
      return {
        code: 200,
        msg: '查询成功',
        data: this.transformResponse(data),
        success: true
      }
    } catch (error) {
      console.error('录像查询失败:', error)
      return {
        code: 500,
        msg: error instanceof Error ? error.message : '查询失败',
        data: { records: [], total: 0, hasMore: false },
        success: false
      }
    }
  }

  /**
   * 转换服务器响应数据格式
   * @param serverData 服务器原始数据
   * @returns 标准化的响应数据
   */
  private transformResponse(serverData: any): PlaybackQueryResponse {
    console.log('转换服务器响应数据:', serverData)
    
    // 检查服务器响应格式 { code, message, data }
    if (serverData && typeof serverData === 'object' && serverData.data) {
      const records = Array.isArray(serverData.data) ? serverData.data : []
      
      const transformedRecords = records.map((item: any, index: number) => {
        // 计算录像时长（秒）
        const startTime = new Date(item.StartTime).getTime()
        const endTime = new Date(item.EndTime).getTime()
        const duration = Math.floor((endTime - startTime) / 1000)
        
        console.log('录像记录原始数据:', item)
        console.log('录像记录EquId:', item.EquId, '类型:', typeof item.EquId)
        
        return {
          id: `record_${item.Index || index}`,
          startTime: item.StartTime,
          endTime: item.EndTime,
          duration: duration,
          filePath: '', // 录像服务器可能不提供文件路径
          fileSize: 0, // 录像服务器可能不提供文件大小
          type: 'normal' as const,
          status: 'available' as const,
          // 添加原始数据字段
          index: item.Index,
          equId: item.EquId,
          subEquId: item.SubEquId,
          channel: item.Channel
        }
      })
      
      return {
        records: transformedRecords,
        total: records.length,
        hasMore: false
      }
    }
    // 默认返回空数据
    return {
      records: [],
      total: 0,
      hasMore: false
    }
  }

  /**
   * 批量查询多个设备的录像记录
   * @param queries 查询参数数组
   * @returns 所有设备的录像记录
   */
  async batchQueryVodRecords(queries: PlaybackQueryParams[]): Promise<ApiResponse<PlaybackQueryResponse[]>> {
    try {
      const promises = queries.map(query => this.queryVodRecords(query))
      const results = await Promise.all(promises)
      
      const allRecords: PlaybackRecord[] = []
      let totalCount = 0
      let hasMore = false

      results.forEach(result => {
        if (result.success && result.data) {
          allRecords.push(...result.data.records)
          totalCount += result.data.total
          if (result.data.hasMore) {
            hasMore = true
          }
        }
      })

      return {
        code: 200,
        msg: '批量查询成功',
        data: [{
          records: allRecords,
          total: totalCount,
          hasMore
        }],
        success: true
      }
    } catch (error) {
      console.error('批量录像查询失败:', error)
      return {
        code: 500,
        msg: error instanceof Error ? error.message : '批量查询失败',
        data: [],
        success: false
      }
    }
  }

  /**
   * 生成回放token
   * @param params 回放token参数
   * @returns 生成的token字符串
   */
  generatePlaybackToken(params: PlaybackTokenParams): string {
    const { deviceId = 0, subEquId, startTime, endTime } = params
    
    // 将本地时间格式转换为所需的格式 (YYYYMMDDTHHMMSSZ)
    const formatTime = (localTime: string): string => {
      // 输入格式: YYYY-MM-DDTHH:mm:ss
      // 输出格式: YYYYMMDDTHHMMSSZ
      return localTime.replace(/[-:]/g, '').replace('T', 'T') + 'Z'
    }
    
    const formattedStartTime = formatTime(startTime)
    const formattedEndTime = formatTime(endTime)
    
    // 生成token: pb_d{deviceId}_c{subEquId}_s{startTime}_e{endTime}
    const token = `pb_d${deviceId}_c${subEquId}_s${formattedStartTime}_e${formattedEndTime}`
    
    console.log('生成回放token:', {
      params,
      formattedStartTime,
      formattedEndTime,
      token
    })
    
    return token
  }

  /**
   * 获取回放流地址
   * @param nvrId NVR ID，用于确定服务器
   * @param token 回放token
   * @returns 回放流地址信息
   */
  async getPlaybackStreamId(nvrId: number, token: string): Promise<ApiResponse<PlaybackStreamIdResponse>> {
    try {
      console.log('获取回放流地址:', { nvrId, token })
      
      // 构建回放流地址查询URL
      const server = this.getStreamServerByNvrId(nvrId)
      if (!server) {
        throw new Error(`未找到NVR ID ${nvrId} 对应的流媒体服务器`)
      }

      let baseUrl: string
      if (import.meta.env.DEV) {
        // 开发环境使用代理
        baseUrl = `/playback${API_CONFIG.ENDPOINTS.PLAYBACK.PLAYBACK_STREAM_ID}`
      } else {
        // 生产环境直接访问录像服务器
        const protocol = API_CONFIG.PLAYBACK_SERVER.PROTOCOL
        const host = server.ip
        const port = this.recordStreamPort || API_CONFIG.PLAYBACK_SERVER.PORT
        baseUrl = `${protocol}://${host}:${port}${API_CONFIG.ENDPOINTS.PLAYBACK.PLAYBACK_STREAM_ID}`
      }

      const url = `${baseUrl}?token=${encodeURIComponent(token)}`
      
      console.log('回放流地址查询URL:', url)
      console.log('环境模式:', import.meta.env.DEV ? '开发环境(使用代理)' : '生产环境(直接访问)')
      
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        signal: AbortSignal.timeout(API_CONFIG.REQUEST_CONFIG.TIMEOUT)
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data: PlaybackStreamIdResponse = await response.json()
      
      console.log('回放流地址响应:', data)
      
      return {
        code: 200,
        msg: '获取回放流地址成功',
        data,
        success: true
      }
    } catch (error) {
      console.error('获取回放流地址失败:', error)
      return {
        code: 500,
        msg: error instanceof Error ? error.message : '获取回放流地址失败',
        data: {
          code: -1,
          message: '获取失败',
          stream_id: ''
        },
        success: false
      }
    }
  }

  /**
   * 获取录像服务器状态
   * @param nvrId NVR ID，用于确定服务器
   * @returns 服务器状态信息
   */
  async getServerStatus(nvrId: number): Promise<ApiResponse<{ online: boolean; responseTime: number }>> {
    try {
      const startTime = Date.now()
      const baseUrl = this.buildPlaybackUrl(nvrId)
      const response = await fetch(baseUrl, {
        method: 'HEAD',
        signal: AbortSignal.timeout(5000) // 5秒超时
      })
      const responseTime = Date.now() - startTime

      return {
        code: 200,
        msg: '服务器状态正常',
        data: {
          online: response.ok,
          responseTime
        },
        success: true
      }
    } catch (error) {
      return {
        code: 500,
        msg: '服务器连接失败',
        data: {
          online: false,
          responseTime: -1
        },
        success: false
      }
    }
  }

  /**
   * 录像播放控制接口
   * @param token 回放token
   * @param streamId 流ID（从stream_id中提取，如从"/xylive/pb_d0_c35_s20251017T000000Z_e20251017T235959Z/551c5078.flv"中提取"551c5078"）
   * @param action 控制动作：seek、pause、play
   * @param arg1 seek时的绝对时间（格式：YYYY-MM-DD HH:mm:ss），其他动作时为空
   * @param arg2 保留参数，暂时无用
   * @returns 控制结果
   */
  async controlPlayback(
    token: string, 
    streamId: string, 
    action: 'seek' | 'pause' | 'play', 
    arg1: string = '', 
    arg2: string = ''
  ): Promise<ApiResponse<any>> {
    try {
      console.log('录像播放控制:', { token, streamId, action, arg1, arg2 })
      
      // 构建控制接口URL
      let baseUrl: string
      if (import.meta.env.DEV) {
        // 开发环境使用代理
        baseUrl = `/playback/nvrserver/v1/record/control/${token}/${streamId}`
      } else {
        // 生产环境直接访问录像服务器
        // 这里需要根据实际情况确定服务器地址
        const protocol = API_CONFIG.PLAYBACK_SERVER.PROTOCOL
        const host = 'localhost' // 需要根据实际情况配置
        const port = this.recordStreamPort || API_CONFIG.PLAYBACK_SERVER.PORT
        baseUrl = `${protocol}://${host}:${port}/nvrserver/v1/record/control/${token}/${streamId}`
      }

      console.log('录像播放控制URL:', baseUrl)
      
      // 构建请求体
      const requestBody = {
        action,
        arg1,
        arg2
      }
      
      console.log('录像播放控制请求体:', requestBody)
      
      const response = await fetch(baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
        signal: AbortSignal.timeout(API_CONFIG.REQUEST_CONFIG.TIMEOUT)
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()
      
      console.log('录像播放控制响应:', data)
      
      return {
        code: 200,
        msg: '控制命令执行成功',
        data,
        success: true
      }
    } catch (error) {
      console.error('录像播放控制失败:', error)
      return {
        code: 500,
        msg: error instanceof Error ? error.message : '控制命令执行失败',
        data: null,
        success: false
      }
    }
  }
}

// 创建单例实例
export const playbackApiService = new PlaybackApiService()

// 导出便捷方法
export const queryVodRecords = (params: PlaybackQueryParams) => 
  playbackApiService.queryVodRecords(params)

export const batchQueryVodRecords = (queries: PlaybackQueryParams[]) => 
  playbackApiService.batchQueryVodRecords(queries)

export const getPlaybackServerStatus = (nvrId: number) => 
  playbackApiService.getServerStatus(nvrId)

export const setPlaybackStreamServers = (servers: StreamServer[], port: string) => 
  playbackApiService.setStreamServers(servers, port)

export const generatePlaybackToken = (params: PlaybackTokenParams) => 
  playbackApiService.generatePlaybackToken(params)

export const getPlaybackStreamId = (nvrId: number, token: string) => 
  playbackApiService.getPlaybackStreamId(nvrId, token)

export const controlPlayback = (
  token: string, 
  streamId: string, 
  action: 'seek' | 'pause' | 'play', 
  arg1: string = '', 
  arg2: string = ''
) => playbackApiService.controlPlayback(token, streamId, action, arg1, arg2)

export default playbackApiService
